import edu.ucdavis.genomics.metabolomics.binbase.connector.references.pubchem.PubchemSubstanceSDFResolver
import org.apache.log4j.Logger
import edu.ucdavis.genomics.metabolomics.binbase.connector.references.sdf.*
import edu.ucdavis.genomics.metabolomics.binbase.connector.references.chebi.ChebiContentResolver
import edu.ucdavis.genomics.metabolomics.binbase.connector.references.kegg.KeggResolver

//configuration file
def config = new ConfigSlurper().parse(new File('grails-app/conf/PathConfiguration.groovy').toURL())

Logger logger = Logger.getLogger("ImportKegg")

logger.info "import kegg files"
String tempDir = config.files.kegg.mols

//first import mol files to generate inchi --> kegg id association
FileHelper.workOnDir(tempDir, {File file ->
  KeggFinder sub = new KeggFinder()
  sub.id = file.getName().replaceAll(".mol", "")

  if (sub.id.matches("C[0-9]{5}")) {
    SdfToInchi.sdfToInchi(new FileInputStream(file), sub)
  }
  else {
    logger.debug "skip, file doesn't match pattern ${file}/${sub.id}"
  }

}, logger, ".mol")

tempDir = config.outputDirectory + "/kegg"

//now import kegg files to create kegg id --> * assosciations
FileHelper.workOnDir(tempDir, {File file ->
  String id = file.getName().replaceAll(".txt", "")

  if (id.matches("C[0-9]{5}")) {
    KeggResolver resolver = new KeggResolver()
    resolver.prepare file

    String cas = resolver.getCasId()

    Kegg kegg = Kegg.findByKeggId(id)

    if (kegg != null) {
      Compound compound = Compound.findByInchi(kegg.compound.inchi)

      CompoundHelper.updateChebiId(logger, compound, resolver.getChebiId())
      CompoundHelper.updateSID(logger, compound, resolver.getPubchemId())
      CompoundHelper.addSynonym(resolver.getNames(), logger, compound)
      CompoundHelper.updatesTheCasNumber(resolver.getCasId(), compound, logger)

      if (resolver.getFormula() != null) {
        if (resolver.getFormula().size() > 0) {
          compound.setFormula(resolver.getFormula())
        }
      }

      compound = CompoundHelper.saveCompound(compound, logger)

      CompoundHelper.aquireStatistic()
    }
    else {
      logger.warn("sorry no compound found for ${id}")
    }
  }
  else {
    logger.debug "skip, file doesn't match pattern ${file}/${id}"
  }

}, logger, ".txt")

class KeggFinder implements InchFinder {

  String id = ""

  void foundInchi(String s, Map<Object, Object> objectObjectMap) {
    Logger logger = Logger.getLogger("ImportKegg")

    SDFContentResolver resolver = new SDFContentResolver()
    resolver.prepare objectObjectMap

    Compound compound = CompoundHelper.getCompound(resolver.getInchi(), resolver.getInchiKey(), logger)
    CompoundHelper.updateKegg(logger, compound, id)

    CompoundHelper.saveCompound compound, logger

    CompoundHelper.aquireStatistic()

  }
}
